# coding:utf-8
from odoo import models, fields, api, _


class GroupOrder(models.Model):
    _name = 'sale.order'
    _inherit = ["sale.order"]


    begin_order_id = fields.Many2one("sale.order", string=u"Begin Order",
                                     copy=True, domain="[('partner_id','=',partner_id)]")
    begin_order_count = fields.Integer(compute='_compute_begin_order', string='Receptions', default=0)
    begin_order_ids = fields.Many2many('sale.order', compute='_compute_begin_order', string='Receptions', copy=False, store=False)
    is_copy = fields.Boolean('Is Copy', default=False, copy=False)

    def _compute_begin_order(self):
        for so in self:
            begin_order_ids = self.env['sale.order'].search([('begin_order_id', '=', so.begin_order_id.id)])
            so.begin_order_ids = begin_order_ids
            so.begin_order_count = len(begin_order_ids)

    @api.multi
    def action_view_begin_order(self):
        self.ensure_one()
        action = self.env.ref('sale.action_orders').read()[0]
        if self.begin_order_id.id:
            action['domain'] = [('begin_order_id', 'in', self.begin_order_ids.ids)]
        return action

    @api.multi
    def write(self, vals):
        if vals.get('begin_order_id') is not None and not vals.get('begin_order_id'):
            vals['begin_order_id'] = self.id
        return super(GroupOrder, self).write(vals)

    @api.model
    def create(self, vals):
        res = super(GroupOrder, self).create(vals)
        if not vals.get('begin_order_id', False):
            res.begin_order_id = res.id
        return res



